package org.example.myleet.p1282;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<List<Integer>> groupThePeople(int[] groupSizes) {
        int n = groupSizes.length;
        List<Integer>[] groups = new List[n + 1];
        for (int i = 0; i < n; ++i) {
            int groupSize = groupSizes[i];
            if (null == groups[groupSize]) {
                groups[groupSize] = new ArrayList<>();
            }
            groups[groupSize].add(i);
        }
        List<List<Integer>> res = new ArrayList<>();
        for (int groupSize = 1; groupSize <= n; ++groupSize) {
            List<Integer> group = groups[groupSize];
            if (null == group) {
                continue;
            }
            if (group.size() <= groupSize) {
                res.add(group);
            } else {
                int j = 0;
                while (j < group.size()) {
                    List<Integer> subGroup = new ArrayList<>(groupSize);
                    for (int i = 0; i < groupSize; ++i) {
                        subGroup.add(group.get(j++));
                    }
                    res.add(subGroup);
                }
            }
        }
        return res;
    }
}
